package com.net;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.json.JSONObject;
import org.xutils.HttpManager;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.ex.HttpException;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;



/**
 *  Http请求操作类
 * @author tangtang
 *
 */
public class HttpRequestUtil {

	private static final int TIME_OUT = 15000;
	public static final int HTTP_POST = 0;
	public static final int HTTP_GET = 1;
	
	
	private HttpRequest param;
	private int httpMethod;
	HttpRonspontCallBack callBack;
	public HttpRequestUtil(HttpRequest param,int httpMethod,HttpRonspontCallBack callBack) {
		this.httpMethod = httpMethod;
		this.param = param;
		this.callBack = callBack;
	}
	
	public void HttpRequest(){
	
		RequestParams requestParams = new RequestParams(param.SERVICE_URL);
		for (int i = 0; i < param.params.size(); i++) {
			requestParams.addBodyParameter(param.params.get(i).key,param.params.get(i).value);
		}
		Log.e("", "" + requestParams.toJSONString());
		requestParams.setConnectTimeout(TIME_OUT);
		//requestParams.setHeader(arg0, arg1);
		x.http().request(httpMethod == 0 ?HttpMethod.POST : HttpMethod.GET, requestParams, new Callback.CommonCallback<String>() {

			@Override
			public void onCancelled(CancelledException arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {			
				Log.e("错误提示", "错误提示");	
					try {			
						HttpResponse result = new HttpResponse();
						if (arg0 instanceof HttpException) {
							
							HttpException ex = (HttpException) arg0;
							
							Log.e("getCode", "" + ex.getCode());
							Log.e("getMessage", ex.getMessage());
							Log.e("getResult", ex.getResult());
							
							result.errorMsg = ex.getMessage();
							
						}else{
							result.errorMsg = "连接失败，请检查网络";
						}
						callBack.callBack(result);
					} catch (Exception e) {
						e.printStackTrace();
					}
			}

			@Override
			public void onFinished() {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(String result) {

				
				Log.e("result", "" + result);
				
				try {
					
					JSONObject ob = new JSONObject(result.toString());
					HttpResponse response = new HttpResponse();
					response.success = ob.getBoolean("success");
					if (!response.success) {
						
						response.errorMsg = ob.getString("errorMsg");
					}	
					if (ob.has("result")) {
						response.content = ob.getString("result");
						Log.e("response.content", "" + response.content);
					}
					
					
					callBack.callBack(response);
				} catch (Exception e) {
					e.printStackTrace();
					HttpResponse response = new HttpResponse();
					response.errorMsg = "数据解析错误";
					callBack.callBack(response);
				}
				
			}
		});
	}
	
	
	public HttpResponse contentWebservice(){
		HttpResponse response = new HttpResponse();
		try {
			StringBuffer sb = new StringBuffer();
			sb.append("");

			if (param.params.size() > 0) {
				for(int i = 0;i < param.params.size();i++){

					//sb.append(param.params.get(i).key+"="+URLEncoder.encode(parameters.getValue(i))+"&");
					
					sb.append(param.params.get(i).key+"="+ URLEncoder.encode(param.params.get(i).value,"UTF-8")+"&");
					//sb.append(param.params.get(i).key+"="+ param.params.get(i).value +"&");
				}
				if(sb.length() > 0){
					sb.deleteCharAt(sb.length()-1);
				}
			}
			String postUrl = null;
			HttpURLConnection conn = null;
			
			postUrl = param.SERVICE_URL + param.methorid ;
			
			Log.e("参数",postUrl + "?" +sb.toString());
			
			URL url = new URL(postUrl + "?" + sb.toString());
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(false);
			conn.setConnectTimeout(TIME_OUT);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			
//			DataOutputStream out = new DataOutputStream(conn.getOutputStream());
//			
//			out.writeBytes(sb.toString());
//			out.close();
		
		
//				Log.e("连接返回code", ""+conn.getResponseCode());
			if (conn.getResponseCode() == 200) {
				InputStream is = conn.getInputStream();
				
				StringBuffer ss = new StringBuffer();
				byte[] bb  = new byte[1024 * 1024 * 100];
				int f = -1;
				while((f = is.read(bb)) > 0){
					String s = new String(bb, 0, f);
					ss.append(s);
				}
				
				Log.e("数据", ss.toString());
				

				
				response.success = true;
				
				response.content = ss.toString();
				Log.e("response.content", "" + response.content);
			}else{
				response.errorMsg = "连接失败，请检查网络";
			}
				
				
				
			
		} catch (Exception e) {
			e.printStackTrace();
			response.success = false;
			response.errorMsg = "连接失败，请检查网络";
		}
		
		return response;
	}
	
	public interface HttpRonspontCallBack{
		void callBack(HttpResponse result);
	}
}
